package cn.bincker.mycaptcha.letter;

import cn.bincker.mycaptcha.basic.AnswerStorage;
import cn.bincker.mycaptcha.basic.CaptchaGuard;
import cn.bincker.mycaptcha.basic.impl.DefaultCaptchaBackgroundCutter;
import cn.bincker.mycaptcha.basic.impl.DefaultCaptchaGuard;
import cn.bincker.mycaptcha.basic.impl.DefaultCaptchaServiceImpl;
import cn.bincker.mycaptcha.basic.impl.SessionAnswerStorage;
import cn.bincker.mycaptcha.letter.controller.LetterCaptchaController;
import cn.bincker.mycaptcha.letter.entity.LetterAnswer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@SuppressWarnings("SpringFacetCodeInspection")
@Configuration
@ConditionalOnProperty(value = "my-captcha.letter.enabled", havingValue = "true")
@EnableConfigurationProperties(LetterCaptchaProperties.class)
public class LetterCaptchaConfiguration {

    @Bean
    public AnswerStorage<LetterAnswer> answerStorage(LetterCaptchaProperties properties){
        return new SessionAnswerStorage<>(properties) {
            @Override
            public String getName() {
                return "LETTER";
            }
        };
    }

    @Bean
    public CaptchaGuard captchaGuard(LetterCaptchaProperties properties, AnswerStorage<LetterAnswer> answerStorage){
        var answerResolver = new LetterVerifyRequestAnswerResolver();
        return new DefaultCaptchaGuard(properties, new LetterCaptchaVerifier(answerResolver, answerStorage));
    }

    @Bean
    public LetterCaptchaController controller(LetterCaptchaProperties properties, AnswerStorage<LetterAnswer> answerStorage){
        var cacheManager = new LetterCacheManagerImpl(properties);
        cacheManager.reload();
        var factory = new LetterCaptchaFactory(properties, new DefaultCaptchaBackgroundCutter(properties), cacheManager);
        var service = new DefaultCaptchaServiceImpl<>(factory, cacheManager,answerStorage);
        return new LetterCaptchaController(service, properties);
    }
}
